<template>
  <view class="container">
    <!-- 地图区域 -->
    <view class="map-container">
      <map
        id="map"
        class="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :scale="14"
        show-location
        @markertap="handleMarkerTap"
      ></map>
    </view>

    <!-- 设备列表 -->
    <view class="store-list">
      <view class="search-box">
        <input
          type="text"
          v-model="searchKeyword"
          placeholder="搜索门店"
          class="search-input"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </view>

      <scroll-view scroll-y class="store-scroll">
        <view
          v-for="store in storeList"
          :key="store.id"
          class="store-item"
          @click="handleStoreClick(store)"
        >
          <view class="store-info">
            <text class="store-name">{{ store.name }}</text>
            <text class="store-address">{{ store.address }}</text>
            <view class="store-meta">
              <text class="store-distance">{{ store.distance }}km</text>
              <text
                class="store-status"
                :class="{ 'status-open': store.isOpen }"
              >
                {{ store.isOpen ? "营业中" : "已关闭" }}
              </text>
            </view>
          </view>
          <view class="store-actions">
            <button class="action-btn" @click.stop="handleNavigate(store)">
              导航
            </button>
            <button class="action-btn" @click.stop="handleCall(store)">
              电话
            </button>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

// 地图中心点
const latitude = ref(30.572815);
const longitude = ref(104.066803);

// 搜索关键词
const searchKeyword = ref("");

// 地图标记点
const markers = ref([
  {
    id: 1,
    latitude: 30.572815,
    longitude: 104.066803,
    title: "银河商城总店",
    iconPath: "/static/marker.png",
    width: 32,
    height: 32,
    callout: {
      content: "银河商城总店\n营业时间：10:00-22:00",
      color: "#000000",
      fontSize: 14,
      borderRadius: 4,
      bgColor: "#ffffff",
      padding: 8,
      display: "ALWAYS",
    },
  },
]);

// 门店列表数据
const storeList = ref([
  {
    id: 1,
    name: "银河商城总店",
    address: "成都市锦江区红星路三段1号",
    distance: 0.5,
    isOpen: true,
    phone: "028-12345678",
    latitude: 30.572815,
    longitude: 104.066803,
  },
  {
    id: 2,
    name: "银河商城春熙店",
    address: "成都市锦江区春熙路299号",
    distance: 1.2,
    isOpen: true,
    phone: "028-87654321",
    latitude: 30.658815,
    longitude: 104.086803,
  },
  {
    id: 3,
    name: "银河商城太古里店",
    address: "成都市锦江区东大街下东大街段166号",
    distance: 1.5,
    isOpen: true,
    phone: "028-12345679",
    latitude: 30.662815,
    longitude: 104.096803,
  },
]);

// 获取当前位置
const getCurrentLocation = () => {
  uni.getLocation({
    type: "gcj02",
    success: (res) => {
      latitude.value = res.latitude;
      longitude.value = res.longitude;
      // 更新地图中心点
      const mapContext = uni.createMapContext("map");
      mapContext.moveToLocation({
        success: () => {
          console.log('移动到当前位置成功');
        },
        fail: (error) => {
          console.error('移动到当前位置失败：', error);
        }
      });
      
      // 计算与各个门店的距离
      storeList.value.forEach(store => {
        store.distance = calculateDistance(
          res.latitude,
          res.longitude,
          store.latitude,
          store.longitude
        );
      });
      
      // 按距离排序
      storeList.value.sort((a, b) => a.distance - b.distance);
    },
    fail: () => {
      uni.showToast({
        title: "获取位置失败",
        icon: "error",
      });
    },
  });
};

// 计算两点之间的距离（km）
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
  const R = 6371; // 地球半径，单位km
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  return Number(distance.toFixed(1)); // 保留一位小数
};

// 处理标记点点击
const handleMarkerTap = (e: any) => {
  const marker = markers.value.find((m) => m.id === e.markerId);
  if (marker) {
    // 可以显示更多信息或执行其他操作
    console.log("点击了标记点：", marker.title);
  }
};

// 处理门店点击
const handleStoreClick = (store: any) => {
  // 移动地图到选中的门店位置
  const mapContext = uni.createMapContext("map");
  mapContext.moveToLocation({
    latitude: store.latitude,
    longitude: store.longitude,
    success: () => {
      console.log('移动到门店位置成功');
    },
    fail: (error) => {
      console.error('移动到门店位置失败：', error);
    }
  });
};

// 处理导航
const handleNavigate = (store: any) => {
  uni.openLocation({
    latitude: store.latitude,
    longitude: store.longitude,
    name: store.name,
    address: store.address,
  });
};

// 处理电话
const handleCall = (store: any) => {
  uni.makePhoneCall({
    phoneNumber: store.phone,
  });
};

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: "请输入搜索关键词",
      icon: "none",
    });
    return;
  }

  const keyword = searchKeyword.value.toLowerCase();
  const filteredStores = storeList.value.filter(store => 
    store.name.toLowerCase().includes(keyword) || 
    store.address.toLowerCase().includes(keyword)
  );

  if (filteredStores.length === 0) {
    uni.showToast({
      title: "未找到相关门店",
      icon: "none",
    });
  } else {
    // 更新地图标记
    markers.value = filteredStores.map(store => ({
      id: store.id,
      latitude: store.latitude,
      longitude: store.longitude,
      title: store.name,
      iconPath: "/static/marker.png",
      width: 32,
      height: 32,
      callout: {
        content: `${store.name}\n营业时间：10:00-22:00`,
        color: "#000000",
        fontSize: 14,
        borderRadius: 4,
        bgColor: "#ffffff",
        padding: 8,
        display: "ALWAYS",
      },
    }));

    // 如果有搜索结果，将地图中心移动到第一个结果的位置
    if (filteredStores.length > 0) {
      const mapContext = uni.createMapContext("map");
      mapContext.moveToLocation({
        latitude: filteredStores[0].latitude,
        longitude: filteredStores[0].longitude,
      });
    }
  }
};

// 页面加载时获取位置
onMounted(() => {
  getCurrentLocation();
});
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.map-container {
  flex: 1;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.store-list {
  height: 40vh;
  background-color: #ffffff;
  border-radius: 20px 20px 0 0;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.search-box {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-input {
  flex: 1;
  height: 36px;
  background-color: #f5f5f5;
  border-radius: 18px;
  padding: 0 15px;
  font-size: 14px;
}

.search-btn {
  width: 80px;
  height: 36px;
  background-color: #007aff;
  color: #ffffff;
  border-radius: 18px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.store-scroll {
  height: calc(100% - 51px);
}

.store-item {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.store-info {
  flex: 1;
  margin-right: 15px;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  display: block;
}

.store-address {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
  display: block;
}

.store-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.store-distance {
  font-size: 12px;
  color: #999;
}

.store-status {
  font-size: 12px;
  color: #ff4d4f;
}

.status-open {
  color: #52c41a;
}

.store-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-btn {
  width: 60px;
  height: 28px;
  font-size: 12px;
  padding: 0;
  margin: 0;
  line-height: 28px;
  background-color: #f0f0f0;
  color: #666;
  border-radius: 14px;
}
</style>
